package com.base.cn.platform.os.controller.manage.main;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.AdminFunctionUtils;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.function.SysFunctionService;
import com.base.cn.platform.os.service.manage.sysUser.SysUserService;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 后台入口Controller
 *
 * @author s.li
 * @create 2018-02-28 15:46
 */
@Controller
public class MainController extends AdminBaseController {
    @Autowired
    private SysFunctionService sysFunctionService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/")
    public String home(){
        return "redirect:/admin/manage/index";
    }


    /**
     * 后台系统首页入口
     * @param request HttpServletRequest
     * @return
     */
    @RequestMapping("/admin/manage/index")
    public String index(HttpServletRequest request) throws UnsupportedEncodingException {
        //获取用户
        JsonObject loginUser = loginUtil.getLoginUser(request);
        //获取用户真名
        Map<String, Object> map = gson.fromJson(loginUser, new TypeToken<Map<String, Object>>() {}.getType());
        request.setAttribute("ralName",map.get("ralName"));
        //获取头像
        if(ObjectUtils.isNotEmpty(map.get("imageJson"))){
            Map<String, Object> imageMap = gson.fromJson(URLDecoder.decode(map.get("imageJson").toString(),"utf-8"),new TypeToken<Map<String,Object>>(){}.getType());
            request.setAttribute("imageMap",imageMap);
        }
        //获取用户是否已做引导
        request.setAttribute("guideStatus",map.get("guideStatus"));

        TreeMap<String,String> h5MobileMap = sysConfigService.getSysConfigContext(ConfigName.H5AMOBILE);
        TreeMap<String,String> appDowMap =sysConfigService.getSysConfigContext(ConfigName.APPDOW);
        TreeMap<String,String> smallAppMap =sysConfigService.getSysConfigContext(ConfigName.SMALLAPP);
        request.setAttribute("h5MobileMap",h5MobileMap);
        request.setAttribute("appDowMap",appDowMap);
        request.setAttribute("smallAppMap",smallAppMap);
        return this.resultPage("/manage/main/index");
    }

    /**
     * 获取所有权限
     * @param request
     * @return
     */
    @RequestMapping("/admin/manage/findAllSysUserFunction")
    @ResponseBody
    public Map<String,Object> findAllSysUserFunction(HttpServletRequest request){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        //查询用户权限
        List<Map<String,Object>> adminPageAllFunctionList = sysFunctionService.findAdminPageAllFunction(userId);
        return ResultUtil.SUCCESS(adminPageAllFunctionList);
    }

    /**
     * 获取页面跳转后的菜单
     * @param url      跳转的URL
     */
    @RequestMapping("/admin/manage/getRedirectMenu")
    @ResponseBody
    public Map<String,Object> getRedirectMenu(HttpServletRequest request,@RequestParam(value = "url") String url) {
        if(StringUtils.isNotEmpty(url)){
            String contextPath = request.getRequestURL().toString().split(request.getRequestURI())[0];
            url = url.replaceAll(contextPath,"").replaceAll("//","/");
        }
        //查询系统中所有url不空的权限
        List<Map<String,Object>> allFunction = sysFunctionService.findAllCacheSysFunctionList();
        //获取访问面包屑
        List<Map<String,Object>> functionLink = AdminFunctionUtils.getRequestLink(url,allFunction);
        if(ObjectUtils.isNotEmpty(functionLink)){
            return ResultUtil.SUCCESS(functionLink);
        }
        return ResultUtil.ERROR("没有操作权限，跳转失败");
    }

    /**
     * 修改用户引导状态
     * @param request 请求对象
     * @param guideStatus 用户引导状态 1-已引导，2-未引导
     */
    @RequestMapping("/admin/manage/updateSysUserGuideStatus")
    @ResponseBody
    public Map<String,Object> updateSysUserGuideStatus(HttpServletRequest request,
                                                       @RequestParam("guideStatus") Integer guideStatus){
        BigDecimal userId = loginUtil.getLoginUserId(request);
        sysUserService.updateSysUserGuideStatus(userId,guideStatus);
        this.updateGuideStatusCache(request,guideStatus);
        return ResultUtil.SUCCESS();
    }

    /**
     * 修改登录用户引导状态缓存
     * @param request
     */
    private void updateGuideStatusCache(HttpServletRequest request,Integer guideStatus){
        String sin = WebUtils.getCookie(request, CommonConstants.ADMIN_LOGIN_COOKIE);
        JsonObject sysUser = loginUtil.getLoginUser(request);
        Map<String, Object> map = gson.fromJson(sysUser, new TypeToken<Map<String, Object>>() {}.getType());
        map.put("guideStatus",guideStatus);
        if(StringUtils.isNotEmpty(sin)){
            customCacheChannel.set(J2CacheRegion.ONE_DAY_REGION.getKey(),sin,gson.toJson(map));
        }
    }
}
